//
//  ChatContentUtils.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/11/4.
//

import Foundation
class ChatContentUtils {
    //不带指令。也就是纯文本
    static func getMessagesList(active:Bool, list : [ChatBean], botRoleBean: RoleBean,
                                userRoleBean: RoleBean,time: TimeInterval,
                                model: String?) -> [MessagesV2] {
        let lastRoleType = configManager.getConfig().AiConfig.getLastRoleType(mode: model)
        
        var listMsg : [MessagesV2] = []
        
        let defaultDesc = AiDescribeManager.shared.getConfig().chatDescDefault ?? ""
        let defaultEndDescribe = AiDescribeManager.shared.getConfig().chatEndDescDefault ?? ""
        
        let rule = defaultDesc.formatAiChatAll(botRoleBean, time) //这个要放最后，针对全部内容进行 名字替换
        
        listMsg.append(MessagesV2("system", botRoleBean.name ?? "", rule))
        
        var listChatMsg :[MessagesV2] = []
        //添加聊天内容(倒序遍历)
        for it in list.reversed() {
            if (it.type == IChatType.END.rawValue) {
                //遇到结束的直接跳出循环
                break
            }
            if (it.role != nil) {
                let type = it.role?.isBot() == true ? "assistant" : "user"
                let roleBean = it.role?.isBot() == true ?  botRoleBean : userRoleBean
                let chatMessageBean = ChatMessageBean()
                chatMessageBean.name = roleBean.name
                chatMessageBean.time =  "\(TimeUtils.getDate(time: it.time, format: "yyyy-MM-dd")) \(TimeUtils.getWeekStr(time: it.time)) " +
                "\(TimeUtils.getTimePeriod(time: it.time))\(TimeUtils.getDate(time: it.time, format: "HH:mm"))"
                
                switch(it.contentType) {
                case IChatContentType.TYPE_EMOJI_PICTURE.rawValue:
                    let emojiPicture = configManager.getConfig().getAiDescribe().emojiPictureDescribe ?? ""
                    let desc = emojiPicture.formatAiChatContent(it.content ?? "")
                    let text = desc.formatAiChat(botRoleBean, time)
//                    var picture: EmojiPictureBean? = nil
//                    do {
//                        picture = try fromJson(it.extra ?? "", EmojiPictureBean.self)
//                    } catch {}
                    chatMessageBean.desc = text
                    //如果有聊天格式，那么内容传key, 没有聊天格式，那么内容应该传图片详情
//                    chatMessageBean.content = chatFormatStr.isEmpty == false ? (picture?.key ?? text) : text
                    chatMessageBean.content = text
                    chatMessageBean.type = "image"
                    break
                case IChatContentType.TYPE_PICTURE.rawValue:
                    let emojiPicture = configManager.getConfig().getAiDescribe().emojiPictureDescribe ?? ""
                    let desc = emojiPicture.formatAiChatContent(it.content ?? "")
                    let text = desc.formatAiChat(botRoleBean, time)
//                    var picture: EmojiPictureBean? = nil
//                    do {
//                        picture = try fromJson(it.extra ?? "", EmojiPictureBean.self)
//                    } catch {}
                    chatMessageBean.desc = text
                    //如果有聊天格式，那么内容传key, 没有聊天格式，那么内容应该传图片详情
//                    chatMessageBean.content = chatFormatStr.isEmpty == false ? (picture?.key ?? text) : text
                    chatMessageBean.content = text
                    chatMessageBean.type = "image"
                    break
                default:
                    let text = it.content ?? ""
                    chatMessageBean.content = text
                    chatMessageBean.type = "text"
                    break
                    
                }
                
                //如果有聊天格式，那么内容用chatMessageBean格式，没有则使用文本内容
//                let text = (chatFormatStr.isEmpty == false ? toJson(chatMessageBean) : chatMessageBean.content) ?? ""
                let text = chatMessageBean.content ?? ""
                //如果为空则不添加
                if (text.isEmpty == false) {
                    listChatMsg.insert(MessagesV2(type, roleBean.name ?? "", text), at: 0)
                }
            }
        }
        listMsg.append(contentsOf: listChatMsg)
        
        if (defaultEndDescribe.isEmpty == false) {
            var mRule = defaultEndDescribe
            //指定ai回复
            if (active) {
                mRule = defaultEndDescribe + "\n\n" + (AiDescribeManager.shared.getConfig().activeChatDesc ?? "")
            }
            listMsg.append(MessagesV2(lastRoleType, userRoleBean.name ?? "", mRule.formatAiChatAll(botRoleBean, time, replace: "{{chatDesc}}", replaceStr : RoleBean.getChatDescDefault(botRoleBean))))
        } else if (active) {
            //指定ai回复
            let mRule = configManager.getConfig().getAiDescribe().activeChatDesc ?? ""
            listMsg.append(MessagesV2(lastRoleType, userRoleBean.name ?? "", mRule.formatAiChatAll(botRoleBean, time, replace: "{{chatDesc}}", replaceStr : RoleBean.getChatDescDefault(botRoleBean))))
        }
        return listMsg
    }
    
    //互动模式
    static func getMessagesNewList(active:Bool, list : [ChatBean], botRoleBean: RoleBean,
                                   userRoleBean: RoleBean,time: TimeInterval,
                                   model: String?) -> [MessagesV2] {
        let lastRoleType = configManager.getConfig().AiConfig.getLastRoleType(mode: model)
        
        var listMsg : [MessagesV2] = []
        
        let defaultDesc = AiDescribeManager.shared.getConfig().chatDesc ?? ""
        let defaultEndDescribe = AiDescribeManager.shared.getConfig().chatEndDesc ?? ""
        
        let rule = defaultDesc.formatAiChatAll(botRoleBean, time) //这个要放最后，针对全部内容进行 名字替换
        
        listMsg.append(MessagesV2("system", botRoleBean.name ?? "", rule))
        
        var listChatMsg :[MessagesV2] = []
        //添加聊天内容(倒序遍历)
        for it in list.reversed() {
            if (it.type == IChatType.END.rawValue) {
                //遇到结束的直接跳出循环
                break
            }
            if (it.role != nil) {
                let type = it.role?.isBot() == true ? "assistant" : "user"
                let roleBean = it.role?.isBot() == true ?  botRoleBean : userRoleBean
                let chatMessageBean = ChatMessageBean()
                chatMessageBean.name = roleBean.name
                chatMessageBean.time =  "\(TimeUtils.getDate(time: it.time, format: "yyyy-MM-dd")) \(TimeUtils.getWeekStr(time: it.time)) " +
                "\(TimeUtils.getTimePeriod(time: it.time))\(TimeUtils.getDate(time: it.time, format: "HH:mm"))"
                //需要系统指令提醒
                switch(it.contentType) {
                case IChatContentType.TYPE_ACTION.rawValue:
                    let text = "(系统提示：\"\(it.role?.name ?? "")\"使用了动作指令功能) " + it.getPatStr()
                    listChatMsg.insert(MessagesV2(lastRoleType, userRoleBean.name ?? "", text), at: 0)
                    break
                default:
                    break
                }
                //通用
                switch(it.contentType) {
                case IChatContentType.TYPE_EMOJI_PICTURE.rawValue:
                    let emojiPicture = configManager.getConfig().getAiDescribe().emojiPictureDescribe ?? ""
                    let desc = emojiPicture.formatAiChatContent(it.content ?? "")
                    let text = desc.formatAiChat(botRoleBean, time)
                    var picture: EmojiPictureBean? = nil
                    do {
                        picture = try fromJson(it.extra ?? "", EmojiPictureBean.self)
                    } catch {}
                    chatMessageBean.desc = text
                    //如果有聊天格式，那么内容传key, 没有聊天格式，那么内容应该传图片详情
                    chatMessageBean.content = picture?.key
                    chatMessageBean.type = IAiContentType.IMAGE.rawValue
                    break
                case IChatContentType.TYPE_PICTURE.rawValue:
                    let emojiPicture = configManager.getConfig().getAiDescribe().emojiPictureDescribe ?? ""
                    let desc = emojiPicture.formatAiChatContent(it.content ?? "")
                    let text = desc.formatAiChat(botRoleBean, time)
                    var picture: EmojiPictureBean? = nil
                    do {
                        picture = try fromJson(it.extra ?? "", EmojiPictureBean.self)
                    } catch {}
                    chatMessageBean.desc = text
                    //如果有聊天格式，那么内容传key, 没有聊天格式，那么内容应该传图片详情
                    chatMessageBean.content = picture?.key
                    chatMessageBean.type = IAiContentType.IMAGE.rawValue
                    break
                case IChatContentType.TYPE_VOICE_MESSAGE.rawValue:
                    let text = it.content ?? ""
                    chatMessageBean.content = text
                    chatMessageBean.type = IAiContentType.VOICE_MESSAGE.rawValue
                    break
                case IChatContentType.TYPE_CONTENT_TARGET.rawValue:
                    var quoteReply = ChatMessageBean.Quote()
                    let targetChat = it.targetChat
                    quoteReply.target_id = targetChat?.objectId
                    quoteReply.target_sender = targetChat?.role?.name
                    quoteReply.target_content = targetChat?.content
                    quoteReply.reply_content = it.content
                    chatMessageBean.quote_reply = quoteReply
                    chatMessageBean.type = IAiContentType.TEXT.rawValue
                    break
                case IChatContentType.TYPE_ACTION.rawValue:
                    if let pat = try? fromJson(it.extra, ChatMessageBean.Pat.self) {
                        if ((pat.content ?? "")?.isEmpty == true) {
                            chatMessageBean.action = pat.action
                            chatMessageBean.suffix = pat.suffix
                        } else {
                            chatMessageBean.content = pat.content
                        }
                        chatMessageBean.type = IAiContentType.TYPE_ACTION.rawValue
                    }
                    break
                default:
                    let text = it.content ?? ""
                    chatMessageBean.content = text
                    chatMessageBean.type = IAiContentType.TEXT.rawValue
                    break
                    
                }
                
                //(id: 11111) [{"type":"ai_image","content":"夕阳下的海边，金色的阳光洒在沙滩上，海浪轻轻拍打着海岸，远处有几只海鸥飞翔。"}]
                //用时间戳+ 数组的格式，方便ai识别
                let text = "(id:\(it.objectId ?? "") \(toJson([chatMessageBean]) ?? "")"
                listChatMsg.insert(MessagesV2(type, roleBean.name ?? "", text), at: 0)
            }
        }
        listMsg.append(contentsOf: listChatMsg)
        
        if (defaultEndDescribe.isEmpty == false) {
            var mRule = defaultEndDescribe
            //指定ai回复
            if (active) {
                mRule = defaultEndDescribe + "\n\n" + (AiDescribeManager.shared.getConfig().activeChatDesc ?? "")
            }
            listMsg.append(MessagesV2(lastRoleType, userRoleBean.name ?? "", mRule.formatAiChatAll(botRoleBean, time, replace: "{{chatDesc}}", replaceStr : RoleBean.getChatDesc(botRoleBean))))
        } else if (active) {
            //指定ai回复
            let mRule = configManager.getConfig().getAiDescribe().activeChatDesc ?? ""
            listMsg.append(MessagesV2(lastRoleType, userRoleBean.name ?? "", mRule.formatAiChatAll(botRoleBean, time, replace: "{{chatDesc}}", replaceStr : RoleBean.getChatDesc(botRoleBean))))
        }
        return listMsg
    }
}
